﻿using DefeatEpidemic.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DefeatEpidemic.API.Lib
{
    public class AccountLib
    {
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetToken(string str)
        {
            string token = "";
            DateTime UTC = DateTime.Now;
            var payload = new Dictionary<string, object>
                {
                    {"sub",""},
                    //{"jti",Guid.NewGuid().ToString() },//JWT ID,JWT的唯一标识
                    {"iat", JwtHelper.ConvertDateTimeToInt(UTC) },//JWT颁发的时间
                    {"issuer","tony"},//签发者
                    {"audience", str},//jwt的接收该方，非必须              
                    {"exp",JwtHelper.ConvertDateTimeToInt(UTC.AddDays(7))},//JWT生命周期 
                
                };
            string secret = ConfigurationHelper.GetSectionValue("TokenSecret");
            JwtHelper.EncryptToken(payload, secret, out token);
            return token;
        }
        /// <summary>
        /// 获取openid
        /// </summary>
        /// <param name="loginCode"></param>
        /// <returns></returns>
        public static Response GetOpenid(string loginCode)
        {
            Response resp = new Response();
            if (string.IsNullOrEmpty(loginCode))
            {
                resp.code = 4010;
                resp.message = "loginCode不可为空";
                return resp;
            }
            string app_id = ConfigurationHelper.GetSectionValue("AppId");
            string app_secret = ConfigurationHelper.GetSectionValue("AppSecret");
            Dictionary<string, object> dic = WinxinHelper.GetWxUserBaseInfo(app_id, app_secret, loginCode);
            if (dic == null)
            {
                resp.code = 4011;
                resp.message = "获取openid失败";
            }
            else
            {
                resp.code = 1;
                resp.data = dic;
            }
            return resp;
        }

        /// <summary>
        /// 确定绑定状态，记录登录日志
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="rd_session"></param>
        /// <param name="nick_name"></param>
        /// <param name="avatar"></param>
        /// <returns></returns>
        //public static async Task<Response> ConfirmBindStatus(string openid, string rd_session, string nick_name = "", string avatar = "")
        //{
        //    Response resp = new Response() { code = 1 };
            
        //    string wx_web = System.Configuration.ConfigurationManager.AppSettings["wx_web"];
        //    var oauth = _context.Find(u => u.open_id == openid);
        //    if (!string.IsNullOrEmpty(nick_name) && !string.IsNullOrEmpty(avatar))
        //    {
        //        oauth.nick_name = nick_name;
        //        oauth.avatar = avatar;
        //        await wxoauthManager.UpdateAsync(oauth);
        //    }
        //    if (oauth.type > 0)
        //    {
        //        resp.message = "微信已绑定";
        //        resp.data = new { token = rd_session, open_id = oauth.open_id, is_bind = true, member_id = oauth.member.id, role_type = oauth.member.MemberType, wx_web };
        //    }
        //    else//没有进行微信绑定
        //    {
        //        //resp.code = 0;
        //        resp.message = "success";
        //        bool is_verification = false;
        //        if (!string.IsNullOrEmpty(oauth.mobile))
        //            is_verification = true;
        //        resp.data = new { token = rd_session, open_id = oauth.open_id, is_bind = false, is_verification = is_verification, wx_web };
        //    }
        //    await AddLoginLog(oauth);
        //    return resp;
        //}

        ///// <summary>
        ///// 添加授权登录日志
        ///// </summary>
        ///// <param name="oauth"></param>
        ///// <returns></returns>
        //private static async Task AddLoginLog(WxOauth oauth)
        //{
        //    try
        //    {
        //        var member = oauth.member;
        //        var loginlogModel = new LoginLog()
        //        {
        //            member = member,
        //            user_name = member.RealName,
        //            remark = "微信登陆",
        //            type = member.MemberType
        //        };
        //        LoginLogManager llm = new LoginLogManager();
        //        await llm.AddAsync(loginlogModel);
        //    }
        //    catch (Exception ex)
        //    {
        //        //记录下日志即可，不抛出错误
        //        //Common.LogHelper.WriteLog("error:" + ex.Message);
        //        Logger.Default.Warn("warn:登录日志写入出错", ex);
        //    }
        //}
    }
}
